<?php
/**
 * 图片生成缩略图和打水印
 *
 * ============================================================================
 * 版权所有: (c) 2009-2011，<UEShop Inc>，并保留所有权利。
 * 网站地址: http://www.ueshop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用；
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 *
 * @author      cmpan
 * @copyright   Copyright (c) 2009-2011 UEShop Inc. (http://www.ueshop.cn)
 * @license     http://www.ueshop.cn/1_0.txt
 */
@ini_set("memory_limit","256M");  // 处理大图片的时候要很大的内存

class UE_Image {

	protected $_attachInfo = '';
	protected $_targetFile = '';
	protected $_imageCreateFromFunc = '';
	protected $_imageFunc = '';
	protected $_attach = array();
	protected $_animatedGif = 0;
	/**
	 * 缩略图宽
	 *
	 * @var int
	 */
	//public $thumbWidth = 90;
	
	/**
	 * 缩略图高
	 *
	 * @var int
	 */
	//public $thumbHeight = 100;

	/**
	 * 初始化图片信息
	 *
	 * @param string $targetFile
	 * @param string $attach
	 */
	function __construct($targetFile, $attach = array()) {
		if (!function_exists('gd_info')) {
			throw new Exception('你的php没有使用gd2扩展,不能处理图片');
		}

		$this->_targetFile = $targetFile;
		$this->_attach = $attach;
		$this->_attachInfo = @getimagesize($targetFile);

		switch($this->_attachInfo['mime']) {
			case 'image/jpeg':
				$this->_imageCreateFromFunc = function_exists('imagecreatefromjpeg') ? 'imagecreatefromjpeg' : '';
				$this->_imageFunc = function_exists('imagejpeg') ? 'imagejpeg' : '';
				break;
			case 'image/gif':
				$this->_imageCreateFromFunc = function_exists('imagecreatefromgif') ? 'imagecreatefromgif' : '';
				$this->_imageFunc = function_exists('imagegif') ? 'imagegif' : '';
				break;
			case 'image/png':
				$this->_imageCreateFromFunc = function_exists('imagecreatefrompng') ? 'imagecreatefrompng' : '';
				$this->_imageFunc = function_exists('imagepng') ? 'imagepng' : '';
				break;
		}

		$this->_attach['size'] = empty($this->_attach['size']) ? @filesize($targetFile) : $this->_attach['size'];

		if($this->_attachInfo['mime'] == 'image/gif') {
			$fp = fopen($targetFile, 'rb');
			$targetFileContent = fread($fp, $this->_attach['size']);
			fclose($fp);
			$this->_animatedGif = strpos($targetFileContent, 'NETSCAPE2.0') === false ? 0 : 1;
		}
	}

	/**
	 * 生成缩略图
	 * 宽度不小于$thumbWidth或高度不小于$thumbHeight的图片生成缩略图
	 * 缩略图和被提取缩略图的文件放于同一目录，文件名为“被提取缩略图文件.thumb.jpg”
	 *
	 * @param int $thumbWidth
	 * @param int $thumbHeight
	 */
	function thumb($thumbWidth, $thumbHeight, $thumbFile = '') {		
		$imageCreateFromFunc = $this->_imageCreateFromFunc;
		$imageFunc = $this->_imageFunc;	

		list($imgW, $imgH) = $this->_attachInfo;

		// 只有大于某个范围的图片才用缩略图,否则复制原图
		if(!$this->_animatedGif) {
			$attachImage = $imageCreateFromFunc($this->_targetFile);

			$xRatio = $thumbWidth / $imgW;  // 宽比率
			if ($imgW >= $thumbWidth || $imgH >= $thumbHeight) {				
				// 高需要截掉
				if(($xRatio * $imgH) > $thumbHeight) {
					$imgH = ($imgW / $thumbWidth) * $thumbHeight;
				} else {
					// 宽需要截掉
					$imgW = ($imgH / $thumbHeight) * $thumbWidth;
				}
			}
			
			// 缩略图一律用jpg格式文件
			$thumbFile || $thumbFile = $this->_targetFile.".thumb.{$thumbWidth}x{$thumbHeight}.jpg";
			if (!is_dir(dirname($thumbFile))) {
				mkdir(dirname($thumbFile), 0755, true);
			}

			$thumbImage = imagecreatetruecolor($thumbWidth, $thumbHeight);

			// 重采样拷贝部分图像并调整大小到$thumbImage
			imageCopyreSampled($thumbImage, $attachImage ,0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgW, $imgH);

			if($this->_attachInfo['mime'] == 'image/jpeg') {
				$imageFunc($thumbImage, $thumbFile, 100);
			} else {
				$imageFunc($thumbImage, $thumbFile);
			}

			$this->_attach['thumbed'] = 1;
			
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 打水印
	 * 只用gif/png图片做水印，jpg不能设置透明，故不用
	 *
	 * @param string $watermarkFile 水印图片
	 * @param int $watermarkPlace 水印放置位置 1:左上, 2：中上， 3右上, 4：左中， 5：中中， 6：右中，7：左下， 8：中下，9右下
	 * @param int $watermarkQuality  被打水印后的新图片(相对于打水印前)质量百分比
	 */
	function watermark($watermarkFile = 'images/logo.gif', $watermarkPlace = 9, $watermarkQuality = 75) {
		$imageCreateFromFunc = $this->_imageCreateFromFunc;
		$imageFunc = $this->_imageFunc;
		list($imgW, $imgH) = $this->_attachInfo;
		
		$watermarkInfo	= @getimagesize($watermarkFile);
		$watermarkLogo	= ('image/png' == $watermarkInfo['mime']) ? @imageCreateFromPNG($watermarkFile) : @imageCreateFromGIF($watermarkFile);

		if(!$watermarkLogo) {
			return;
		}

		list($logoW, $logoH) = $watermarkInfo;
		$wmwidth = $imgW - $logoW;
		$wmheight = $imgH - $logoH;

		if(is_readable($watermarkFile) && $wmwidth > 10 && $wmheight > 10 && !$this->_animatedGif) {
			switch($watermarkPlace) {
				case 1:
					$x = +5;
					$y = +5;
					break;
				case 2:
					$x = ($imgW - $logoW) / 2;
					$y = +5;
					break;
				case 3:
					$x = $imgW - $logoW - 5;
					$y = +5;
					break;
				case 4:
					$x = +5;
					$y = ($imgH - $logoH) / 2;
					break;
				case 5:
					$x = ($imgW - $logoW) / 2;
					$y = ($imgH - $logoH) / 2;
					break;
				case 6:
					$x = $imgW - $logoW;
					$y = ($imgH - $logoH) / 2;
					break;
				case 7:
					$x = +5;
					$y = $imgH - $logoH - 5;
					break;
				case 8:
					$x = ($imgW - $logoW) / 2;
					$y = $imgH - $logoH - 5;
					break;
				case 9:
					$x = $imgW - $logoW - 5;
					$y = $imgH - $logoH - 5;
					break;
			}

			$dstImage = imagecreatetruecolor($imgW, $imgH);
			$targetImage = @$imageCreateFromFunc($this->_targetFile);
			imageCopy($dstImage, $targetImage, 0, 0, 0, 0, $imgW, $imgH);
			imageCopy($dstImage, $watermarkLogo, $x, $y, 0, 0, $logoW, $logoH);

			if($this->_attachInfo['mime'] == 'image/jpeg') {
				$imageFunc($dstImage, $this->_targetFile, $watermarkQuality);
			} else {
				$imageFunc($dstImage, $this->_targetFile);
			}

			$this->_attach['size'] = filesize($this->_targetFile);
		}
	}
}